package com.qingyun.edusysteam.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qingyun.edusysteam.dto.FeedbackDTO;
import com.qingyun.edusysteam.dto.FeedbackPhotoDTO;
import com.qingyun.edusysteam.dto.Result;
import com.qingyun.edusysteam.entity.Feedback;
import com.qingyun.edusysteam.entity.FeedbackPhoto;
import com.qingyun.edusysteam.mapper.FeedbackMapper;
import com.qingyun.edusysteam.mapper.FeedbackPhotoMapper;
import com.qingyun.edusysteam.service.IFeedbackService;
import com.qingyun.edusysteam.utils.ImageUploadUtil;
import com.qingyun.edusysteam.utils.UserHolder;
import com.qingyun.edusysteam.vo.FeedbackVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课堂反馈 服务实现类
 * </p>
 *
 * @author your_name
 * @since 2025-08-23
 */
@Slf4j
@Service
public class FeedbackServiceImpl extends ServiceImpl<FeedbackMapper, Feedback> implements IFeedbackService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserHolder userHolder;
    @Autowired
    private FeedbackPhotoMapper feedbackPhotoMapper;
    
    @Value("${file.upload.base-path:D:/QingYunEduSystem/EduSysteam/uploads/}")
    private String baseUploadPath;

    @Override
    public Result listByStudent(Long studentId, String token) {
        Long userId=userHolder.getUserId();
        // 直接使用多表查询，返回简要信息VO列表
        List<FeedbackVO> list = baseMapper.briefList(studentId, userId, null);
        return Result.ok(list == null ? new ArrayList<>() : list);
    }

    @Override
    public Result postFeedback(FeedbackDTO feedbackDTO) {
        try {
            // 创建反馈记录
            Feedback feedback = BeanUtil.copyProperties(feedbackDTO, Feedback.class);
            feedback.setScheduleId(feedbackDTO.getScheduleId());
            feedback.setStudentId(feedbackDTO.getStudentId());
            feedback.setCreateTime(LocalDateTime.now());
            feedback.setUpdateTime(LocalDateTime.now());
            feedback.setTeacherId(userHolder.getUserId());
            
            // 保存反馈记录
            baseMapper.insert(feedback);
            Long feedbackId = feedback.getId();
            log.info("反馈提交成功，ID: {}", feedbackId);
            
            // 处理图片数据
            if (feedbackDTO.getPhotos() != null && !feedbackDTO.getPhotos().isEmpty()) {
                saveFeedbackPhotos(feedbackId, feedbackDTO.getPhotos());
                log.info("保存反馈图片成功，共{}张", feedbackDTO.getPhotos().size());
            }
            
            return Result.ok();
        } catch (Exception e) {
            log.error("提交反馈时发生异常", e);
            return Result.fail("提交反馈失败，请重试");
        }
    }
    
    /**
     * 保存反馈图片
     * @param feedbackId 反馈ID
     * @param photos 图片列表
     */
    private void saveFeedbackPhotos(Long feedbackId, List<FeedbackPhotoDTO> photos) {
        for (FeedbackPhotoDTO photoDTO : photos) {
            FeedbackPhoto feedbackPhoto = new FeedbackPhoto();
            feedbackPhoto.setFeedbackId(feedbackId);
            feedbackPhoto.setUrl(photoDTO.getUrl());
            feedbackPhoto.setSortNo(photoDTO.getSortNo());
            feedbackPhoto.setCreateTime(LocalDateTime.now());
            
            feedbackPhotoMapper.insert(feedbackPhoto);
        }
    }
    
    @Override
    public Result uploadFeedbackPhoto(MultipartFile file, String token) {
        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                return Result.fail("请选择要上传的图片文件");
            }
            
            // 验证文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.fail("图片文件大小不能超过5MB");
            }
            
            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !isImageFile(originalFilename)) {
                return Result.fail("只支持jpg、jpeg、png、gif格式的图片文件");
            }
            
            // 创建图片保存目录
            String imageDir = baseUploadPath + "feedback/images/";
            java.io.File dir = new java.io.File(imageDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 使用ImageUploadUtil上传图片
            String fileName = ImageUploadUtil.upload(file, imageDir);
            
            // 构建返回的图片URL
            String imageUrl = "/uploads/feedback/images/" + fileName;
            
            // 返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("url", imageUrl);
            data.put("fileName", fileName);
            data.put("originalName", originalFilename);
            data.put("size", file.getSize());
            
            log.info("图片上传成功: {}", imageUrl);
            return Result.ok(data);
            
        } catch (IllegalArgumentException e) {
            log.warn("图片上传参数错误: {}", e.getMessage());
            return Result.fail(e.getMessage());
        } catch (IOException e) {
            log.error("图片上传IO异常", e);
            return Result.fail("图片上传失败，请重试");
        } catch (Exception e) {
            log.error("图片上传异常", e);
            return Result.fail("图片上传失败，系统异常");
        }
    }
    
    @Override
    public Result uploadFeedbackPhotos(MultipartFile[] files, String token) {
        try {
            // 验证文件数组
            if (files == null || files.length == 0) {
                return Result.fail("请选择要上传的图片文件");
            }
            
            // 限制上传数量
            if (files.length > 9) {
                return Result.fail("最多只能上传9张图片");
            }
            
            // 创建图片保存目录
            String imageDir = baseUploadPath + "feedback/images/";
            java.io.File dir = new java.io.File(imageDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            
            // 批量上传图片
            List<Map<String, Object>> uploadedImages = new ArrayList<>();
            
            for (int i = 0; i < files.length; i++) {
                MultipartFile file = files[i];
                
                try {
                    // 验证单个文件
                    if (file.isEmpty()) {
                        continue; // 跳过空文件
                    }
                    
                    if (file.getSize() > 5 * 1024 * 1024) {
                        log.warn("图片{}大小超过5MB，跳过上传", file.getOriginalFilename());
                        continue;
                    }
                    
                    if (!isImageFile(file.getOriginalFilename())) {
                        log.warn("图片{}格式不支持，跳过上传", file.getOriginalFilename());
                        continue;
                    }
                    
                    // 上传图片
                    String fileName = ImageUploadUtil.upload(file, imageDir);
                    String imageUrl = "/uploads/feedback/images/" + fileName;
                    
                    Map<String, Object> imageData = new HashMap<>();
                    imageData.put("url", imageUrl);
                    imageData.put("fileName", fileName);
                    imageData.put("originalName", file.getOriginalFilename());
                    imageData.put("size", file.getSize());
                    imageData.put("sortNo", i);
                    
                    uploadedImages.add(imageData);
                    
                } catch (Exception e) {
                    log.error("上传第{}张图片失败: {}", i + 1, e.getMessage());
                    // 继续上传其他图片
                }
            }
            
            if (uploadedImages.isEmpty()) {
                return Result.fail("没有成功上传任何图片");
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("images", uploadedImages);
            result.put("count", uploadedImages.size());
            
            log.info("批量上传图片成功，共{}张", uploadedImages.size());
            return Result.ok(result);
            
        } catch (Exception e) {
            log.error("批量上传图片异常", e);
            return Result.fail("批量上传图片失败，系统异常");
        }
    }
    
    @Override
    public List<String> getFeedbackPhotos(Long feedbackId) {
        try {
            List<FeedbackPhoto> photos = feedbackPhotoMapper.selectByFeedbackId(feedbackId);
            List<String> photoUrls = new ArrayList<>();
            
            for (FeedbackPhoto photo : photos) {
                photoUrls.add(photo.getUrl());
            }
            
            return photoUrls;
        } catch (Exception e) {
            log.error("获取反馈图片时发生异常，feedbackId: {}", feedbackId, e);
            return new ArrayList<>();
        }
    }
    
    /**
     * 验证是否为图片文件
     * @param filename 文件名
     * @return 是否为图片文件
     */
    private boolean isImageFile(String filename) {
        if (filename == null || filename.trim().isEmpty()) {
            return false;
        }
        
        String lowerCaseFilename = filename.toLowerCase();
        return lowerCaseFilename.endsWith(".jpg") || 
               lowerCaseFilename.endsWith(".jpeg") || 
               lowerCaseFilename.endsWith(".png") || 
               lowerCaseFilename.endsWith(".gif");
    }
}
